package com.tianxiao.faas.application.web.corner;

import com.tianxiao.faas.api.param.corner.BasePageParam;
import com.tianxiao.faas.api.param.corner.CategoryParam;
import com.tianxiao.faas.api.param.corner.CustomInfoResult;
import com.tianxiao.faas.common.access.Access;
import com.tianxiao.faas.common.result.Result;
import com.tianxiao.faas.common.util.PageUtils;
import com.tianxiao.faas.mapper.dao.CategoryModelMapper;
import com.tianxiao.faas.mapper.model.CategoryModel;
import org.checkerframework.checker.units.qual.C;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/app/admin/category/")
public class CategoryAdminController {
    @Resource
    private CategoryModelMapper categoryModelMapper;

    @RequestMapping(value = "shop/list")
    @Access(access = {"admin"})
    public Result<List<CategoryParam>> list(@RequestBody BasePageParam param) {
        List<CategoryParam> results = new ArrayList<>();
        List<CategoryModel> page = categoryModelMapper.query(0);
        Integer count = 0;
        if (!CollectionUtils.isEmpty(page)) {
            count = page.size();
            page.forEach(e->{
                CategoryParam categoryParam = new CategoryParam();
                categoryParam.setIcon(e.getIcon());
                categoryParam.setId(e.getId());
                categoryParam.setName(e.getName());
                results.add(categoryParam);
            });
        }
        return Result.builder().success(true).data(results).totalCount(count).pageNo(param.getPage())
                .pageSize(param.getPageSize()).totalPage();
    }

    @RequestMapping(value = "shop/save")
    @Access(access = {"admin"})
    public Result<Boolean> save(@RequestBody CategoryParam param) {
        CategoryModel categoryModel = new CategoryModel();
        categoryModel.setId(param.getId());
        categoryModel.setName(param.getName());
        categoryModel.setIcon(param.getIcon());
        categoryModel.setType(0);
        long l = System.currentTimeMillis();
        categoryModel.setUpdated(l);
        if (categoryModel.getId() == null) {
            categoryModel.setCreated(l);
            categoryModelMapper.insertSelective(categoryModel);
        } else {
            categoryModelMapper.updateByPrimaryKeySelective(categoryModel);
        }
        return Result.builder().success(true).data(true);
    }
}
